<template>
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="5" class="fl">
          <el-form-item label="分类">
            <SelectCategory :searchCategoryIdList="searchCategoryIdList" @handleChange="handlechangecategory" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="品牌">
            <el-select class="m-2" placeholder="选择品牌" size="small" style="width: 80%" v-model="brandId">
              <el-option v-for="item in getBrandByCategoryList" :key="item.id" :label="item.brandName"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="handleClick">搜索</el-button>
        <el-button size="small" @click="handleClickReset">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow" class="add-button">
      添 加
    </el-button>
  </div>
  <el-table :data="DeepCategoryBrand" style="width: 100%">
    <el-table-column prop="id" label="ID" v-if="false" />
    <el-table-column prop="categoryName" label="分类" />
    <el-table-column prop="brandName" label="品牌" />
    <el-table-column prop="logo" label="品牌图标">
      <template #default="scope">
        <img :src="scope.row.logo" width="50" />
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column prop="updateTime" label="更新时间" />
    <el-table-column label="操作" align="center" width="200">
      <template #default="scope">
        <el-button type="primary" size="small" @click="updateData(scope.row)">
          修改
        </el-button>
        <el-button type="danger" size="small" @click="remove(scope.row.id)">
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%" @close="cancelEdit">
    <el-form label-width="120px">
      <el-form-item label="分类" style="width: 80%">
        <SelectCategory :searchCategoryIdList="searchCategoryIdList" @handleChange="handlechangecategory" />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select class="m-2" placeholder="选择品牌" size="small" style="width: 30%" v-model="brandId" filterable>
          <el-option v-for="item in brandOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item align="right">
        <el-button type="primary" @click="saveOrUpdate">提交</el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, provide } from 'vue';
import { GetCategoryBrandPageList, DeleteCategoryBrandById, AddCategoryBrand, UpdateCategoryBrand, getBrandByCategoryId ,getCategoryByBrandId} from '@/api/product/categoryBrand';
import { debounce } from '@/utils';
import { useProduct } from '@/pinia/modules/product';
import CategoryApi from '@/api/product/category';
import { deepClone } from '@/utils';
import { GetAllBrandList } from '@/api/product/brand';
import { ElMessage, ElMessageBox } from 'element-plus'
import SelectCategory from '@/components/SelectCategory/selectCategory.vue';
// 缓存的
const appStore = useProduct();
const brandId = ref('');
// 页面加载时
onMounted(() => {
  fetchData();
  findAllBrand();
});

//页面变化
const handleSizeChange = size => {
  pageParams.value.limit = size
  fetchData()
}
const handleCurrentChange = number => {
  pageParams.value.page = number
  fetchData()
}

// 数据模型定义按条件或者查询全部
const defaultForm = {
  brandId: '',
  categoryId: '',
  imageUrl: '',
  logo: '',
  categoryName: '',
  brandName: '',
  createTime: '',
  updateTime: ''
};
const CategoryBrand = ref({ ...defaultForm });

// 分页数据数量和限制
const total = ref(0);
const pageParamsForm = {
  pageNum: 1,
  pageSize: 10,
};
const pageParams = ref(pageParamsForm);

// 深克隆一份查询数据
const DeepCategoryBrand = ref([]);

// 搜索防抖
const handleClick = debounce(() => {
  const { pageNum, pageSize } = pageParams.value;
  const { categoryId } = CategoryBrand.value;

  // 传递 categoryId 和 brandId 参数如果有按条件查询，无就是查全部
  fetchData(pageNum, pageSize, categoryId, brandId.value);
}, 500);

// 重置清空选择的数据防抖
const handleClickReset = debounce(() => {
  resetFilters();
}, 500);

// 分页查询
const fetchData = async ( categoryId, brandId) => {


  // 发起请求
  let response = await GetCategoryBrandPageList(pageParams.value.page,
  pageParams.value.limit, categoryId, brandId);
  console.log("查询的数据", response);
  if (response) {
    CategoryBrand.value = response.data.records;
    total.value = response.data.total;
    DeepCategoryBrand.value = deepClone(CategoryBrand.value);
  } else {
    console.error('获取数据为空');
  }
};

// 调用搜索分类的方法，根据分类id再去找品牌的数据
const searchCategoryIdList = ref([]);
provide('searchCategoryIdList', searchCategoryIdList); // 选择分类

// 选择分类
const handlechangecategory = (lastId, arr) => {
  getBrand(lastId);

};

// 品牌列表根据分类id去查品牌
const getBrandByCategoryList = ref([]);
const getBrand = async (id) => {
  CategoryBrand.value.categoryId = id;
  if (id !== 0) {
    let response = await getBrandByCategoryId(id);
    if (response) {
      getBrandByCategoryList.value = response.data;
      // brandId.value = ''; // 清空之前的选择
    } else {
      console.error('获取数据为空');
    }
  } else {
    getBrandByCategoryList.value = [];
    // brandId.value = ''; // 清空之前的选择
  }
};
// 重置清空
const resetFilters = () => {
  searchCategoryIdList.value = [];
  getBrandByCategoryList.value = [];
  brandId.value = '';
  fetchData();
};


//查询全部品牌
const brandOptions = ref([]);

const findAllBrand = async () => {
  let response = await GetAllBrandList();
  if (response && response.data) {
    brandOptions.value = response.data;
  }
};

//增删改的方法
// 定义是否显示增删改的弹窗状态
const dialogVisible = ref(false)

//定义关闭窗口和点击取消清空之前选择

const cancelEdit = () => {
  searchCategoryIdList.value = [];
  getBrandByCategoryList.value = [];
  brandId.value = '';
  fetchData();
  dialogVisible.value = false;
}

// 定义判断是否有id来添加和修改
const SaveOrUpdateFrom = {
  id: '',
  categoryId: '',
  brandId: '',
  categoryName: '',
  brandName: ''
};


//添加弹窗打开
const addShow = () => {
  SaveOrUpdateFrom.value = []
  dialogVisible.value = true
}


const updateData = async (row) => {
  dialogVisible.value = true;
  SaveOrUpdateFrom.value = deepClone(row);
  const lastId = parseInt(SaveOrUpdateFrom.value.categoryId, 10);
  let list = [lastId]
  const setSearchCategoryIdList = async (id) => {
  console.log("Current ID:", id);
  if (id !== 0 && id != null) {
    const response = await getCategoryByBrandId(id);
    const parentId = parseInt(response.data, 10);
    console.log("Parent ID:", parentId);
    if (parentId !== 0 && parentId != null) {
      list.unshift(parentId);
      console.log("Updated List:", list);
      await setSearchCategoryIdList(parentId);
    }
  }
  searchCategoryIdList.value = list;
  return;
};

  console.log(SaveOrUpdateFrom.value.categoryId)
  await setSearchCategoryIdList(SaveOrUpdateFrom.value.categoryId);
  brandId.value = SaveOrUpdateFrom.value.brandId;
};

// 提交表单判断是否有id来添加和修改
const saveOrUpdate = async  () => {
  if (!SaveOrUpdateFrom.value.id) {

    if(CategoryBrand.value.categoryId === '' ||CategoryBrand.value.categoryId === null||CategoryBrand.value.categoryId === undefined){
        ElMessage.info('请选择分类')
    }else if(brandId.value === ''){
        ElMessage.info('请选择品牌')
    }else{
        //添加
        // 提交表单并传递分类和品牌的 ID
        await saveData(brandId, CategoryBrand.value.categoryId);
    }
  } else {
    //修改
    // 提交表单并传递分类和品牌的 ID
    if(CategoryBrand.value.categoryId === '' ||CategoryBrand.value.categoryId === null||CategoryBrand.value.categoryId === undefined){
        ElMessage.info('请选择分类')
    }else if(brandId.value === ''){
        ElMessage.info('请选择品牌')
    }else{
        //添加
        // 提交表单并传递分类和品牌的 ID
        const id = SaveOrUpdateFrom.value.id;
        console.log(CategoryBrand.value.categoryId)
        await UpdateCategoryBrandById(id, brandId, CategoryBrand.value.categoryId);
    }
    

  }
}

// 新增
const saveData = async (brandId, categoryId) => {
  if (brandId && categoryId) {
    console.log(brandId.value)
    console.log(categoryId)
    // 提交表单
    await AddCategoryBrand(brandId.value, categoryId);

    dialogVisible.value = false; // 关闭对话框
    ElMessage.success('操作成功');
    fetchData(); // 重新获取数据
  } else if (brandId) {
    ElMessage.error('请选择分类');
  } else {
    ElMessage.error('请选择品牌');
  }
}

//修改 
const UpdateCategoryBrandById = async (id, brandId, categoryId) => {

  // 提交表单
  await UpdateCategoryBrand(id, brandId.value, categoryId);
  dialogVisible.value = false; // 关闭对话框
  ElMessage.success('操作成功');
  cancelEdit()
  fetchData(); // 重新获取数据
}


//删除
const remove = async (id) => {
  const confirmResult = await ElMessageBox.confirm(
    '此操作将永久删除该品牌, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).catch((err) => err);

  if (confirmResult !== 'confirm') {
    return ElMessage.info('已取消删除');
  }

  await DeleteCategoryBrandById(id);
  ElMessage.success('删除成功');
  fetchData(); // 重新获取数据
}
</script>

<style scoped>
.fl {
  margin-left: -30px;
}

.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
